#include "./Include/my_thread.h"
#include "boost/format.hpp"
#include "boost/array.hpp"
#include <syslog.h>
#include "my_exception.h"
#include <string>
#include "./Include/global.h"
using std::string;
//线程函数
void TaskThread(boost::asio::ip::tcp::socket* pSock)
{
    
    boost::system::error_code ignored_error;    //错误信息
    string clientIP = pSock->remote_endpoint().address().to_string();
    unsigned int clientPort = pSock->remote_endpoint().port();
    boost::format fmt;      //格式化字符串
    string msg,recv_data;
    boost::array<char, 1024> data_buffer{ '\0' };

    fmt = boost::format("客户端[%s:%d]响应成功，当前连接数[%d]");
    fmt %clientIP%clientPort%curThreadNum;
    msg = fmt.str();
    syslog(LOG_INFO,msg.c_str());

    try
    {
        //发送问候语
         pSock->write_some(boost::asio::buffer("Hello this is reflex server,you can send 1023 byte char"),ignored_error);

        //首发数据
        while(true)
        {
            //收数据	
	        int size = pSock->read_some(boost::asio::buffer(data_buffer), ignored_error);
	        if (ignored_error)
        	{
	        	boost::format fmt("收包失败,错误码[%d],%s");
	        	fmt% ignored_error.value();
	        	fmt% boost::system::system_error(ignored_error).what();
	        	std::string errTemp = fmt.str();
		        throw my_exception() << err_str(errTemp);
	        }
	        recv_data = data_buffer.data();
            fmt = boost::format("客户端[%s:%d]，收包数据:%s");
            fmt%clientIP%clientPort%recv_data;
            syslog(LOG_INFO,fmt.str().c_str());

            // 向socket写入数据
	        pSock->write_some(boost::asio::buffer(recv_data), ignored_error);
        	if (ignored_error)
        	{
	        	boost::format fmt("发包失败,错误码[%d],%s");
        		fmt% ignored_error.value();
	        	fmt% boost::system::system_error(ignored_error).what();
	        	std::string errTemp = fmt.str();
        		throw my_exception() << err_str(errTemp);
        	}	            
        }
    }
    catch(my_exception &e)
    {
        msg = *boost::get_error_info<err_str>(e);
        boost::format fmt("客户端[%s:%d],%s");     
        fmt%clientIP%clientPort;   
        fmt % (*boost::get_error_info<err_str>(e));
        msg = fmt.str();
        syslog(LOG_INFO,msg.c_str());
        pSock->close();
        delete pSock;
    }

    //客户端线程关闭
    fmt = boost::format ("客户端[%s,%d]线程关闭，当前连接数[%d]");     
        fmt%clientIP%clientPort%curThreadNum;
    msg = fmt.str();
    syslog(LOG_INFO,msg.c_str());    
    curThreadNum--;
}